package com.hmall.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-11-03 11:26
 **/
@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class TokenGlobalFilter implements GlobalFilter, Ordered {
    private final JwtTool jwtTool;
    private final AuthProperties authProperties;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 从请求头获取路径
        String path = request.getPath().toString();
        // 分析path
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return chain.filter(exchange);
            }
        }
        // 从请求头中获取token
        String token = request.getHeaders().getFirst("Authorization");
        // token为空
        if (StrUtil.isEmpty(token)) {
            // 拦截
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        Long userId = null;
        // 解析token
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            // 拦截
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
        }
        // 将userId放到请求头里面
        request.mutate().header("user-info", String.valueOf(userId));
        // 放行
        return chain.filter(exchange);
    }

    /**
     * 过滤器执行顺序，值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
